import Toast from 'tdesign-miniprogram/toast/index';
import {
  getAddressPromise
} from '../../usercenter/address/list/util';
import {
  getOrderDetail,
  refundOrder,
  getPreOrder,
  placeOrder
} from '../../../api/index'

Page({
  data: {
    pageLoading: true,
    order: {}, // 后台返回的原始数据
    _order: {}, // 内部使用和提供给 order-card 的数据
    storeDetail: {},
    countDownTime: null,
    addressEditable: false,
    backRefresh: false, // 用于接收其他页面back时的状态
    formatCreateTime: '', //格式化订单创建时间
    logisticsNodes: [],
    /** 订单评论状态 */
    orderHasCommented: true,
    status: '',
    id: null, //订单id
    info: {},
  },

  onLoad(query) {
    this.setData({
      status: query.status,
      id: query.id
    });
    console.log(query.status, 'status new')
    this.orderNo = query.orderNo;
    this.init();
    this.navbar = this.selectComponent('#navbar');
    this.pullDownRefresh = this.selectComponent('#wr-pull-down-refresh');
  },

  onShow() {
    // 当从其他页面返回，并且 backRefresh 被置为 true 时，刷新数据
    if (!this.data.backRefresh) return;
    this.onRefresh();
    this.setData({
      backRefresh: false
    });
  },

  onPageScroll(e) {
    this.pullDownRefresh && this.pullDownRefresh.onPageScroll(e);
  },

  onImgError(e) {
    if (e.detail) {
      console.error('img 加载失败');
    }
  },

  // 页面初始化，会展示pageLoading
  init() {
    this.setData({
      pageLoading: true
    });
    this.getOrderDetailFn()
  },

  // 页面刷新，展示下拉刷新
  onRefresh() {
    this.init();
    // 如果上一页为订单列表，通知其刷新数据
    const pages = getCurrentPages();
    const lastPage = pages[pages.length - 2];
    if (lastPage) {
      lastPage.data.backRefresh = true;
    }
  },

  // 页面刷新，展示下拉刷新
  onPullDownRefresh_(e) {
    const {
      callback
    } = e.detail;
    return this.getOrderDetailFn().then(() => callback && callback());
  },


  onGoodsCardTap(e) {
    const {
      index
    } = e.currentTarget.dataset;
    const goods = this.data.order.orderItemVOs[index];
    wx.navigateTo({
      url: `/pages/goods/details/index?spuId=${goods.spuId}`
    });
  },

  onEditAddressTap() {
    getAddressPromise()
      .then((address) => {
        this.setData({
          'order.logisticsVO.receiverName': address.name,
          'order.logisticsVO.receiverPhone': address.phone,
          '_order.receiverAddress': address.address,
        });
      })
      .catch(() => {});

    wx.navigateTo({
      url: `/pages/usercenter/address/list/index?selectMode=1`,
    });
  },

  onOrderNumCopy() {
    wx.setClipboardData({
      data: this.data.order.orderNo,
    });
  },

  onDeliveryNumCopy() {
    wx.setClipboardData({
      data: this.data.order.logisticsVO.logisticsNo,
    });
  },

  onToInvoice() {
    wx.navigateTo({
      url: `/pages/order/invoice/index?orderNo=${this.data._order.orderNo}`,
    });
  },

  onSuppleMentInvoice() {
    wx.navigateTo({
      url: `/pages/order/receipt/index?orderNo=${this.data._order.orderNo}`,
    });
  },

  onDeliveryClick() {
    const logisticsData = {
      nodes: this.data.logisticsNodes,
      company: this.data.order.logisticsVO.logisticsCompanyName,
      logisticsNo: this.data.order.logisticsVO.logisticsNo,
      phoneNumber: this.data.order.logisticsVO.logisticsCompanyTel,
    };
    wx.navigateTo({
      url: `/pages/order/delivery-detail/index?data=${encodeURIComponent(
        JSON.stringify(logisticsData),
      )}`,
    });
  },


  clickService() {
    Toast({
      context: this,
      selector: '#t-toast',
      message: '您点击了联系客服',
    });
  },

  onOrderInvoiceView() {
    wx.navigateTo({
      url: `/pages/order/invoice/index?orderNo=${this.orderNo}`,
    });
  },
  getOrderDetailFn() {
    getOrderDetail({
      orderId: this.data.id
    }).then(res => {
      console.log(res, 'ews详情')
      this.setData({
        info: res.data
      })
    })
  },
  goToPay() {
    if (wx.getStorageSync('user_token')) {
      console.log('111')
      this.placeOrderFn()
    } else {
      wx.showToast({
        title: '请先登录',
        icon: 'error'
      })
      wx.switchTab({
        url: '/pages/usercenter/index',
      })
    }
  },
  async placeOrderFn() {
    getPreOrder({
      orderSn: this.data.info.orderSn
    }).then(res => {
      console.log(res.data,
        'w d ')
      delete res?.data.appId
      const obj = {
        ...res?.data
      }
      wx.requestPayment({
        ...obj,
        totalFee: 1,
        success: function (res) {
          // 支付成功后的回调函数  
          console.log('支付成功', res);
          // 更新订单状态等操作  
        },
        fail: function (res) {
          // 支付失败后的回调函数  
          console.log('支付失败', res);
          // 处理支付失败的情况  
        }
      });
    })



  },
  goToPage() {
    wx.switchTab({
      url: '/pages/cart/index',
    })
  },
  refund() {
    console.log(this.data.info.orderSn, this.data.info.allPrice, '退款中')
    refundOrder({
      ordersn: this.data.info.orderSn,
      refundAmount: this.data.info.allPrice
    }).then(res => {
      if (res.code == 200) {
        Toast({
          context: this,
          selector: '#t-toast',
          message: '退款申请已提交',
        });
      }
    })
  }
});